import Database.*;
import Server.Server;
import ServerOutput.OutputManager;
import java.io.*;

public class main {
    //Negaudom visu exceptionu
    public static void main(String[] args) throws Exception {
        String rootDir;
        if(args.length == 1) {
            rootDir = args[0];
        } else {
            rootDir = "C:/domains";
        }
        
        println("Starting server.");
        OutputManager outputManagerObj = new OutputManager(rootDir);
        println("Server root directory set to: " + rootDir);
        
        Database DB = new Database();
        
        Server serverObj = new Server(80, outputManagerObj); 
        Thread mainServerThread = new Thread(serverObj);
        mainServerThread.start();
        println("Server started and listening on port 80... \nType help to get available command list.");
        
        String[] commands = {
            "start - Starts listening for connections.", 
            "stop - Stops listening for connections.",
            "showUsers - Shows all regsitered useres.",
            "addUser [domain] [name] [surname] [password] - Adds user to database and creates domain.",
            "deleteUser [user_id] - Deletes user with spcified id.",
            "exit - Stops listening for connections and exits application."
        };
        
        InputStreamReader converter = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(converter);
        String cmdLine;
        while (true){
            cmdLine = in.readLine();
            
            if(cmdLine.equals("exit")) {
                break;
            }
            
            if(cmdLine.equals("help")) {
                showHelp(commands);
                continue;
            }
            
            if(cmdLine.equals("stop")) {
                if(!mainServerThread.isAlive()) {
                    println("Server is not running.");
                    continue;
                }
                serverObj.stop();
                println("Stopping server...");
                while(!mainServerThread.isAlive()) {}
                 println("Server stopped.");
                continue;
            }
            
            if(cmdLine.equals("start")) {
                if(mainServerThread.isAlive()) {
                    println("Server is already running.");
                    continue;
                }
                mainServerThread = new Thread(serverObj);
                mainServerThread.start();
                println("Server started.");
                continue;
            }
            
            if(cmdLine.equals("showUsers")) {
                try {
                    Row[] userRows = DB.queryRows("SELECT * FROM users");
                    String usersString = "ID | DOMAIN | NAME | SURENAME | PASSWORD | LAST_VISIT\n";
                    for(int i=0; i<userRows.length; i++) {
                        usersString += userRows[i].getColumnValue("id") + " " + userRows[i].getColumnValue("domain") + " " + userRows[i].getColumnValue("name") + " " + userRows[i].getColumnValue("password") + " " + userRows[i].getColumnValue("last_visit");
                        if(i != userRows.length -1) {
                            usersString += "\n";
                        }
                    }
                    println(usersString);
                } catch (Exception e) {
                    println("Failed to show users.");
                }
                continue;
            }
            
            String[] cmdParts = cmdLine.split(" ");
            if(cmdParts.length == 5 && cmdParts[0].equals("addUser")) {
                try {
                    DB.query("INSERT INTO users (domain, name, surname, password, last_visit) VALUES ('"+cmdParts[1]+"', '"+cmdParts[2]+"', '"+cmdParts[3]+"', '"+cmdParts[4]+"', CURRENT_DATE)");
                    println("User added to database");
                    
                   boolean success = (new File(rootDir + "/" + cmdParts[1])).mkdir();
                   if(success) {
                       println("User files directory created at: " + rootDir + "/" + cmdParts[1]);
                   } else {
                       println("Failed to create directory for user files at " + rootDir + "/" + cmdParts[1]);
                   }
                   
                } catch (Exception e) {
                    println("Failed to add user.");
                }
                continue;
            }
            
            if(cmdParts.length == 2 && cmdParts[0].equals("deleteUser")) {
                try {
                    Row userRow = DB.queryRow("SELECT * FROM users WHERE id = '" + cmdParts[1] + "'");
                    DB.query("DELETE FROM pages WHERE user_domain='" + userRow.getColumnValue("domain") + "'");
                    DB.query("DELETE FROM users WHERE id='"+cmdParts[1]+"'");
                    println("User deleted from database.");

                    try {
                        deleteDirectory(new File(rootDir + "/" + userRow.getColumnValue("domain")));
                        println("User files deleted.");
                    } catch(Exception e) {
                        println("Failed to delete user files at: " + rootDir + "/" + userRow.getColumnValue("user_domain"));
                    }
                } catch (Exception e) {
                    println("Failed to delete user.");
                }
                continue;
            }  
        }
        serverObj.stop();
    }
    
    private static void showHelp(String[] commands) {
        String help = "Available commands: \n";
        for(int i=0; i<commands.length; i++) {
            help += commands[i];
            if(i != commands.length - 1) {
                help += "\n";
            }
        }
        println(help);
    }
    
    private static boolean deleteDirectory(File path) {
        if( path.exists() ) {
            File[] files = path.listFiles();
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                  deleteDirectory(files[i]);
                }
                else {
                  files[i].delete();
                }
            }
        }
        return( path.delete() );
    }
    
    private static void println(String s) {
        System.out.println(s);
    }
}